// 云函数入口文件
const cloud = require('wx-server-sdk');

cloud.init();

const db = cloud.database()

/**
 * 错误码说明
 * 0: 成功
 * 1: 队伍ID无效
 * 2: 已经在队伍中
 * 3: 已经发起申请
 * 4: 用户未注册
 * 5: 其他错误
 */
// 云函数入口函数
exports.main = async (event, context) => {
  const postId = event.teamId;
  const wxContext = cloud.getWXContext();
  const openId = wxContext.OPENID;
  console.log('openid', openId);
  // 检查用户是否注册
  var userInfo = await db.collection('user').where({
    _openid: openId
  }).get();
  if (userInfo.data.length == 0) {
    return {
      errCode: 4
    };
  }
  // 检查队伍ID是否合法
  try {
    var teamInfo = await db.collection('post').doc(postId).get();
  } catch (e) {
    return {
      errCode: 1
    };
  }
  console.log('got team', teamInfo);
  // 检查是否已在队伍中
  for (var i in teamInfo.data.members) {
    if (teamInfo.data.members[i] == openId) {
      return {
        errCode: 2
      };
    }
  }
  // if (openId in teamInfo.data.members) {
  //   return {
  //     errCode: 2
  //   };
  // }
  // 检查是否已经发起申请
  var applyStatus = await db.collection('application').where({
    applyer: openId,
    team: postId
  }).get();
  console.log('apply', applyStatus);
  if (applyStatus.data.length != 0) {
    return {
      errCode: 3
    };
  }
  // 发起申请
  var addRes = await db.collection('application').add({
    data: {
      applyer: openId,
      team: postId,
      time: getDateStr(),
      status: 'pending'
    }
  });
  console.log('add res', addRes);
  return {
    errCode: addRes.errMsg == 'collection.add:ok' ? 0 : 5
  };
}

/**
 * @brief 获取当前日期字符串，格式为yyyy-mm-dd
 */
function getDateStr() {
  var d = new Date();
  var date = String(d.getFullYear()) + '-' + String(d.getMonth() + 1) + '-' + String(d.getDate()); // yyyy-mm-dd
  return date;
}